package controller;

import base.Constant;
import bean.ResultBean;
import bean.User;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import service.SystemService;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/")
public class SystemController {

    @Resource
    private SystemService systemService;

    @RequestMapping("index")
    public String index() {
        return "index";
    }

    @RequestMapping("dashboard")
    public String dashboard() {
        return "dashboard";
    }

    @RequestMapping("pieChart")
    public String pieChart() {
        return "pieChart";
    }

    @RequestMapping("lineChart")
    public String lineChart(Model model) {
        List<String> row = Arrays.asList("房租费", "餐饮费", "交通费");
        List<String> column = Arrays.asList("一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月");
        String[][] data = new String[row.size()][column.size()];
        Random random = new Random();
        for (int i = 0; i < row.size(); i++) {
            for (int j = 0; j < column.size(); j++) {
                data[i][j] = String.valueOf(random.nextInt(100));
            }
        }
        ResultBean bean = new ResultBean();
        bean.setRowData(row);
        bean.setColumnData(column);
        bean.setData(data);
        model.addAttribute("result", JSON.toJSONString(bean));
        StringBuilder builder = new StringBuilder();
        for (String rowData : row) {

        }
        String option = String.format(Constant.lineChartTemplate, "费用统计", JSON.toJSONString(row), JSON.toJSONString(column), builder.toString());
        return "lineChart";
    }

    @RequestMapping("loginSubmit")
    public String loginSubmit(String username, String password, HttpSession session) {
        User user = systemService.authenticate(username);
        if (user != null && user.getPassword().equals(password)) {
            session.setAttribute("loginUser", user);
            return "redirect:dashboard";
        }
        return "redirect:index";
    }

    @RequestMapping("logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        session.invalidate();
        return "redirect:index";
    }
}
